#include <stdio.h>
#include <string.h>
#include "reverse_string.h"

void reverseString_recursive(char* a, int st_pos, int end_pos) {
    char tmp;
    
    if (st_pos < end_pos) {
        tmp = *(a + st_pos);
        *(a + st_pos) = *(a + end_pos);
        *(a + end_pos) = tmp;
        reverseString_recursive(a, st_pos + 1, end_pos - 1);
    }
}

void reverseString_iterative(char* a, int st_pos, int end_pos) {
    char tmp;
    
    while (st_pos < end_pos) {
        tmp = *(a + st_pos);
        *(a + st_pos) = *(a + end_pos);
        *(a + end_pos) = tmp;
        st_pos++;
        end_pos--;
    }
}

void reverseWordsInString(char* a) {
    // reverse string first
    int st_pos = 0;
    int end_pos = strlen(a) - 1;    
    reverseString_recursive(a, st_pos, end_pos);

    int pos = 0;
    
    // reverse words
    while (pos <= end_pos) {
        if (a[pos] == ' ') {
            reverseString_recursive(a, st_pos, pos-1);
            st_pos = pos + 1;
        }
        else if (pos == end_pos) {
            reverseString_recursive(a, st_pos, pos);
        }
        pos++;
    }
}

void test_reverse_string() {
	// reverse string (recursive approach)
	char a[] = "This is a text";
	printf("Before reverse: %s\n", a);
	reverseString_recursive(a, 0, strlen(a)-1);
	printf("After reverse (recursive): %s\n\n", a);
	
	// reverse string (iterative approach)
	char b[] = "test string here";
	printf("Before reverse: %s\n", b);
	reverseString_iterative(b, 0, strlen(b)-1);
	printf("After reverse (iterative): %s\n\n", b);
	
	// reverse words in string
	char c[] = "this is the output";
	printf("Before reverse: %s\n", c);
	reverseWordsInString(c);
	printf("After reverse words in string: %s\n\n", c);
}
